package com.bml.architect.sentinel.exceptions;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: baiml
 * @Title: MyFlowException
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:
 * @date: 2021/4/20 11:38
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String result = "";

        System.out.println("+++++++++++++++++++"+e);
        if (e instanceof FlowException) {
            result = "{'code':'100','msg':'接口限流了'}";
        } else if (e instanceof DegradeException) {
            result = "{'code':'101','msg':'服务降级了'}";
        } else if (e instanceof ParamFlowException) {
            result = "{'code':'102','msg':'热点参数限流了'}";
        } else if (e instanceof SystemBlockException) {
            result = "{'code':'102','msg':'触发系统保护规则了'}";
        } else if (e instanceof AuthorityException) {
            result = "{'code':'102','msg':'授权规则不通过'}";
        }
        //返回json数据
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), result);
    }
}
